<?php

namespace App\Handler\WeChat;

use App\Jobs\TempPush;
use App\Models\Hospital;
use App\Models\HospitalTeam;
use App\Models\Qrcodeid;
use App\Models\ScanRecord;
use App\Models\TempPushRecord;
use App\Models\UserLogin;
use App\Wechat\Init;
use App\Wechat\Temp;

class SubscribeHandler
{
    public function __invoke($message, \Closure $next)
    {
        if ($message->Event === 'subscribe' || $message->Event === 'SCAN') {
            $scene = str_replace('qrscene_', '',$message->EventKey);

            if($scene) {
                $qrcodeid = Qrcodeid::query()->where('qrcodeid', $scene)->first();
                if($qrcodeid) {
                    $hospital_id = $qrcodeid->mappingid;
                    $app = new Init();
                    $response = $app->handle('get', '/cgi-bin/user/info', [
                        'openid' => $message->FromUserName,
                        'lang' => 'zh_CN',
                    ]);
                    $unionid = $response['unionid'];
                    $scanRecord = new ScanRecord();
                    $scanRecord->openid = $message->FromUserName;
                    $scanRecord->hospital_id = $hospital_id;
                    $scanRecord->unionid = $unionid;
                    $hospital = Hospital::query()->where('id', $hospital_id)->first();
                    $scanRecord->independent = isset($hospital) ? $hospital->independent : 1;

                    $userLogin = UserLogin::query()->where('unionid', $unionid)->first();
                    $user_id = isset($userLogin) ? $userLogin->user_id : 0;
                    if (!$user_id) {
                        $scanRecord_ord = ScanRecord::query()->where('openid', $message->FromUserName)->first();
                        $user_id = $scanRecord_ord ? $scanRecord_ord->user_id : 0;
                    }
                    $scanRecord->user_id = $user_id;
                    $scanRecord->save();

                    $team = HospitalTeam::query()->where('hospital_id',$hospital->id)->first();
                    $app = new Init();
                    $app->handle('postJson', '/cgi-bin/message/template/send', [
                        'touser' => $message->FromUserName,
                        'template_id' => 'KJKgdarbimWIeuVMAYu1VyurMUOuPve48ywc3RT6uxY',
                        'url' => env('WECHAT_URL'),
                        'miniprogram' => [
                            'appid' => config('easywechat.mini_app.default.app_id'),
                            'pagepath' => 'pages/index/index',
                        ],
                        'data' => [
                            "keyword1" => ['value'=>$team->name],
                            "keyword2" => ['value'=>$hospital->name],
                            "keyword3" => ['value'=>date('Y年m月d日')],
                        ],
                    ]);

                    return "请点击卡片进入小程序添加宝宝/孕妇，签约时请选择置顶社区完成签约";
                }
            }else{
                return "您好，感谢关注儿宝宝！\n\n如果管辖社区卫生服务中心已经开通签约儿保医生服务，回复SQ+社区名称即可获取社区二维码（如：“SQ小红门”，）长按并识别二维码即可签约成功并享受中医儿童健康指导，查看健康体检信息及通知，咨询儿保医生等服务\n\n如需要查询社区名称请访问：".env('WECHAT_URL')."/doctors 查询社区后长按并识别二维码即可\n\n如果社区还没开通此项服务，点击菜单栏 -- 育儿服务 -- 添加宝宝信息,授权成功即可优先免费享有中医儿童健康指导服务";
            }

        }

        return $next($message);
    }
}
